package com.talent.jiwen.http.common;

import android.content.Context;

import com.talent.jiwen.ui.widgets.LoadingDialog;
import com.talent.jiwen.util.LogUtil;
import com.talent.jiwen.util.NetUtils;

import java.net.SocketTimeoutException;

import rx.Subscriber;

/**
 * @author cmw
 * @date 创建时间：2017/8/5
 * @description
 */
public abstract class ProgressSubscriber<T> extends Subscriber<T> implements ProgressCancelListener {


    private Context mContext;
    public ProgressSubscriber(Context context) {
        mContext=context;

    }

    @Override
    public void onCompleted() {
        dismissProgressDialog();

    }
    /**
     * 显示Dialog
     */
    public void showProgressDialog() {

        LoadingDialog.show(mContext);
    }

    @Override
    public void onNext(T t) {
        dismissProgressDialog();
            _onNext(t);
    }

    /**
     * 隐藏Dialog
     */
    private void dismissProgressDialog() {
        LoadingDialog.dismiss(mContext);
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        LogUtil.e("eee", "onError:=== "+e.toString() );
        e.printStackTrace();
        if (!NetUtils.isNetworkAvailable(mContext)) { //这里自行替换判断网络的代码
            _onError("网络不可用");
        } else if (e instanceof SocketTimeoutException) {
            _onError("请求超时，请检查网络");
        } else if (e instanceof ApiException) {
            _onError(e.getMessage());
        }else {
//            Toast.makeText(mContext, "服务端数据异常！", Toast.LENGTH_SHORT).show();
            _onError("服务端数据异常，请稍后重试");
        }
                dismissProgressDialog();
    }

    @Override
    public void onCancelProgress() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }

    protected abstract void _onNext(T t);
    protected abstract void _onError(String message);
}
